package com.danan.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.danan.realtime.app.BaseApp;
import com.danan.realtime.common.Constant;
import com.danan.realtime.function.MyAsyncFunction;
import com.danan.realtime.pojo.TradeSkuOrderBean;
import com.danan.realtime.util.SinkUtil;
import com.danan.realtime.util.TimeUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.math.BigDecimal;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * @author NanHuang
 * @Date 2023/1/26
 */
/*
    解决问题：需要等待上一条数据查询完维度信息，才能查询下一条数据的维度信息。等待时间过长，效率低下
    解决方式：异步查询（多线程 + 多客户端）
*/
public class DwsApp_9_trade_sku_order_window_cache_async extends BaseApp {
    public static void main(String[] args) {
        new DwsApp_9_trade_sku_order_window_cache_async().init(
                5009,
                3,
                "DwsApp_9_trade_sku_order_window",
                Constant.TOPIC_DWD_TRADE_ORDER_DETAIL
        );
    }
    @Override
    public void invoke(StreamExecutionEnvironment env, DataStreamSource<String> ds) {
        // 1 将数据封装为pojo类
        SingleOutputStreamOperator<TradeSkuOrderBean> beanDs = toTradeSkuOrderBean(ds);
        // 2 处理重复数据(由dwd层的left join产生)
        SingleOutputStreamOperator<TradeSkuOrderBean> handledDs = handleDuplicateData(beanDs);
        // 3 进行开窗聚合
        SingleOutputStreamOperator<TradeSkuOrderBean> aggDs = windowAndAgg(handledDs);
        // 4 补充维度信息(聚合后的数据量小，再补充维度信息)
        SingleOutputStreamOperator<TradeSkuOrderBean> resultDs = extendDimInfo(aggDs);
        // 5 将结果写入Clickhouse
        resultDs.addSink(SinkUtil.getClickhouseSink(Constant.TOPIC_DWS_TRADE_SKU_ORDER_WINDOW,TradeSkuOrderBean.class));
    }

    private SingleOutputStreamOperator<TradeSkuOrderBean> extendDimInfo(SingleOutputStreamOperator<TradeSkuOrderBean> ds) {
        SingleOutputStreamOperator<TradeSkuOrderBean> skuInfoDs = AsyncDataStream.unorderedWait(
                ds,
                new MyAsyncFunction<TradeSkuOrderBean>() {
                    @Override
                    public String getTable() {
                        return "dim_sku_info";
                    }

                    @Override
                    public String getId(TradeSkuOrderBean input) {
                        return input.getSkuId();
                    }

                    @Override
                    protected void extendDimInfo(TradeSkuOrderBean data, JSONObject dimInfo) {
                        data.setSkuName(dimInfo.getString("SKU_NAME"));
                        data.setSpuId(dimInfo.getString("SPU_ID"));
                        data.setCategory3Id(dimInfo.getString("CATEGORY3_ID"));
                        data.setTrademarkId(dimInfo.getString("TM_ID"));
                    }
                },
                120,
                TimeUnit.SECONDS
        );

        SingleOutputStreamOperator<TradeSkuOrderBean> spuInfoDs = AsyncDataStream.unorderedWait(
                skuInfoDs,
                new MyAsyncFunction<TradeSkuOrderBean>() {
                    @Override
                    public String getTable() {
                        return "dim_spu_info";
                    }

                    @Override
                    public String getId(TradeSkuOrderBean input) {
                        return input.getSpuId();
                    }

                    @Override
                    protected void extendDimInfo(TradeSkuOrderBean data, JSONObject dimInfo) {
                        data.setSpuName(dimInfo.getString("SPU_NAME"));
                    }
                },
                120,
                TimeUnit.SECONDS
        );

        SingleOutputStreamOperator<TradeSkuOrderBean> tmInfoDs = AsyncDataStream.unorderedWait(
                spuInfoDs,
                new MyAsyncFunction<TradeSkuOrderBean>() {
                    @Override
                    public String getTable() {
                        return "dim_base_trademark";
                    }

                    @Override
                    public String getId(TradeSkuOrderBean input) {
                        return input.getTrademarkId();
                    }

                    @Override
                    protected void extendDimInfo(TradeSkuOrderBean data, JSONObject dimInfo) {
                        data.setTrademarkName(dimInfo.getString("TM_NAME"));
                    }
                },
                120,
                TimeUnit.SECONDS
        );

        SingleOutputStreamOperator<TradeSkuOrderBean> c3InfoDs = AsyncDataStream.unorderedWait(
                tmInfoDs,
                new MyAsyncFunction<TradeSkuOrderBean>() {
                    @Override
                    public String getTable() {
                        return "dim_base_category3";
                    }

                    @Override
                    public String getId(TradeSkuOrderBean input) {
                        return input.getCategory3Id();
                    }

                    @Override
                    protected void extendDimInfo(TradeSkuOrderBean data, JSONObject dimInfo) {
                        data.setCategory3Name(dimInfo.getString("NAME"));
                        data.setCategory2Id(dimInfo.getString("CATEGORY2_ID"));
                    }
                },
                120,
                TimeUnit.SECONDS
        );

        SingleOutputStreamOperator<TradeSkuOrderBean> c2InfoDs = AsyncDataStream.unorderedWait(
                c3InfoDs,
                new MyAsyncFunction<TradeSkuOrderBean>() {
                    @Override
                    public String getTable() {
                        return "dim_base_category2";
                    }

                    @Override
                    public String getId(TradeSkuOrderBean input) {
                        return input.getCategory2Id();
                    }

                    @Override
                    protected void extendDimInfo(TradeSkuOrderBean data, JSONObject dimInfo) {
                        data.setCategory2Name(dimInfo.getString("NAME"));
                        data.setCategory1Id(dimInfo.getString("CATEGORY1_ID"));
                    }
                },
                120,
                TimeUnit.SECONDS
        );

        return AsyncDataStream.unorderedWait(
                c2InfoDs,
                new MyAsyncFunction<TradeSkuOrderBean>() {
                    @Override
                    public String getTable() {
                        return "dim_base_category1";
                    }

                    @Override
                    public String getId(TradeSkuOrderBean input) {
                        return input.getCategory1Id();
                    }

                    @Override
                    protected void extendDimInfo(TradeSkuOrderBean data, JSONObject dimInfo) {
                        data.setCategory1Name(dimInfo.getString("NAME"));
                    }
                },
                120,
                TimeUnit.SECONDS
        );
    }

    private SingleOutputStreamOperator<TradeSkuOrderBean> windowAndAgg(SingleOutputStreamOperator<TradeSkuOrderBean> ds) {
        // 1 创建水印策略
        WatermarkStrategy<TradeSkuOrderBean> strategy = WatermarkStrategy.<TradeSkuOrderBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner((s, l) -> s.getTs())
                .withIdleness(Duration.ofSeconds(60));
        // 2 开窗聚合
        return ds.assignTimestampsAndWatermarks(strategy)
                .keyBy(TradeSkuOrderBean::getSkuId)
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<TradeSkuOrderBean>() {
                    @Override
                    public TradeSkuOrderBean reduce(TradeSkuOrderBean t1, TradeSkuOrderBean t2) throws Exception {
                        t2.setOriginalAmount(t2.getOriginalAmount().add(t1.getOriginalAmount()));
                        t2.setActivityAmount(t2.getActivityAmount().add(t1.getActivityAmount()));
                        t2.setCouponAmount(t2.getCouponAmount().add(t1.getCouponAmount()));
                        t2.setOrderAmount(t2.getOrderAmount().add(t1.getOrderAmount()));
                        return t2;
                    }
                }, new WindowFunction<TradeSkuOrderBean, TradeSkuOrderBean, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow window, Iterable<TradeSkuOrderBean> input, Collector<TradeSkuOrderBean> out) throws Exception {
                        TradeSkuOrderBean result = input.iterator().next();
                        result.setStt(TimeUtil.parseDateStr(window.getStart(),true));
                        result.setEdt(TimeUtil.parseDateStr(window.getEnd(),true));
                        result.setTs(System.currentTimeMillis());
                        out.collect(result);
                    }
                });
    }

    private SingleOutputStreamOperator<TradeSkuOrderBean> handleDuplicateData(SingleOutputStreamOperator<TradeSkuOrderBean> ds) {
        return ds.keyBy(TradeSkuOrderBean::getDetailId)
                .process(new KeyedProcessFunction<String, TradeSkuOrderBean, TradeSkuOrderBean>() {

                    private ValueState<TradeSkuOrderBean> flagData;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        flagData = getRuntimeContext().getState(new ValueStateDescriptor<TradeSkuOrderBean>("flagData", TradeSkuOrderBean.class));
                    }

                    @Override
                    public void processElement(TradeSkuOrderBean value, KeyedProcessFunction<String, TradeSkuOrderBean, TradeSkuOrderBean>.Context ctx, Collector<TradeSkuOrderBean> out) throws Exception {
                        TradeSkuOrderBean lagData = flagData.value();
                        flagData.update(value);
                        if (lagData == null) {
                            out.collect(value);
                        } else {
                            value.setOriginalAmount(value.getOriginalAmount().subtract(lagData.getOriginalAmount()));
                            value.setActivityAmount(value.getActivityAmount().subtract(lagData.getActivityAmount()));
                            value.setCouponAmount(value.getCouponAmount().subtract(lagData.getCouponAmount()));
                            value.setOrderAmount(value.getOrderAmount().subtract(lagData.getOrderAmount()));
                            out.collect(value);
                        }
                    }
                });
    }

    private SingleOutputStreamOperator<TradeSkuOrderBean> toTradeSkuOrderBean(DataStreamSource<String> ds) {
        return ds.map(new RichMapFunction<String, TradeSkuOrderBean>() {
            @Override
            public TradeSkuOrderBean map(String s) throws Exception {
                JSONObject obj = JSON.parseObject(s);
                return TradeSkuOrderBean.builder()
                        .skuId(obj.getString("sku_id"))
                        .detailId(obj.getString("id"))
                        .originalAmount(obj.getBigDecimal("split_original_amount"))
                        .activityAmount(obj.getBigDecimal("split_activity_amount") == null ? new BigDecimal(0) : obj.getBigDecimal("split_activity_amount"))
                        .couponAmount(obj.getBigDecimal("split_coupon_amount") == null ? new BigDecimal(0) : obj.getBigDecimal("split_coupon_amount"))
                        .orderAmount(obj.getBigDecimal("split_total_amount"))
                        .ts(obj.getLong("ts") * 1000)
                        .build();
            }
        });
    }
}
